package com.smart.utils;


import cn.hutool.core.date.LocalDateTimeUtil;
import com.smart.common.exception.SmartException;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * SQL语句可能用到的方法封装
 *
 * @author Administrator
 */
public class SqlUtil {


    /**
     * 查询数据库JSON字段的某个键是否等于给定值
     *
     * @param fieldName 字段名
     * @param value     值
     * @param path      键的路径
     * @return {@code String} 查询条件
     */
    public static String getJsonFieldEqExpr(String fieldName, Object value, String path) {
        if (value instanceof String) {
            return String.format(" %s->'%s' = '%s' ", fieldName, path, value);
        }
        return String.format(" %s->'%s' = %s ", fieldName, path, value);
    }


    /**
     * 日期字符串转换成日期数组
     *
     * @param dateTimeString 日期字符串  字段数据格式示例 2001-01-01,2001-12-31
     * @return {@code DateTime[]}
     */
    public static LocalDateTime[] formatDateTimeRange(String dateTimeString) {
        try {
            String[] dateArray = dateTimeString.split(",");
            LocalDateTime t1 = LocalDateTimeUtil.parse(dateArray[0].concat("T00:00:00.000"));
            LocalDateTime t2 = LocalDateTimeUtil.parse(dateArray[1].concat("T23:59:59.999"));
            return new LocalDateTime[]{t1, t2};
        } catch (Exception e) {
            throw new SmartException("范围查询时间段范围字段值不正确");
        }
    }



    /**
     * 日期字符串转换成日期数组
     *
     * @param dateTimeString 日期字符串  字段数据格式示例 2001-01-01,2001-12-31
     * @return {@code DateTime[]}
     */
    public static LocalDate[] formatDateRange(String dateTimeString) {
        try {
            String[] dateArray = dateTimeString.split(",");
            LocalDate t1 = LocalDateTimeUtil.parseDate(dateArray[0]);
            LocalDate t2 = LocalDateTimeUtil.parseDate(dateArray[1]);
            return new LocalDate[]{t1, t2};
        } catch (Exception e) {
            throw new SmartException("范围查询时间段范围字段值不正确");
        }
    }


}
